import sys
import os
import logging
import re
import json
from typing import Dict, List, Any, Optional, Tuple

# 添加项目根路径到 sys.path
sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..'))

# 导入 MySQLUtil
from shared.utils.MySQLUtil import MySQLUtil

# 设置日志
logger = logging.getLogger(__name__)

def get_对课程设置与社会需求的契合度_总体(
    project_id: int,
    questionnaire_ids: List[int],
    product_code: Optional[str] = None,
    project_code: Optional[str] = None,
    region_code: Optional[str] = None
) -> Dict[str, Any]:
    """
    对课程设置与社会需求的契合度-总体 - 指标计算函数
    
    ## 指标说明
    该指标用于评估课程设置与社会需求的契合程度，通过统计学生问卷中关于"课程设置契合社会需求"问题的回答情况，
    计算选择"很符合"、"符合"和"基本符合"的学生比例，反映课程设置与社会需求的总体匹配度。
    
    ## Args
        project_id (int): 项目ID，用于查询项目配置信息
        questionnaire_ids (List[int]): 问卷ID集合，用于确定数据范围
        product_code (Optional[str]): 产品编码，用于路由到特定计算逻辑
        project_code (Optional[str]): 项目编码，用于路由到特定计算逻辑
        region_code (Optional[str]): 区域编码，用于路由到特定计算逻辑
        
    ## 示例
    ### 输入
    ```json
    {
        "project_id": 6594,
        "questionnaire_ids": [12425, 12426]
    }
    ```
    
    ### 输出
    ```json
    {
        "success": true,
        "message": "ok", 
        "code": 0,
        "result": [
            {
                "calcVals": [
                    {
                        "val": [
                            {
                                "key": "default",
                                "val": "0.7624"
                            }
                        ]
                    }
                ]
            }
        ]
    }
    ```
    """
    logger.info(f"开始计算指标: 对课程设置与社会需求的契合度-总体, 项目ID: {project_id}")
    
    try:
        db = MySQLUtil()  

        # 1. 查询项目配置信息
        project_sql = """
        SELECT client_code, item_year, dy_target_items, split_tb_paper 
        FROM client_item 
        WHERE id = %s
        """
        project_info = db.fetchone(project_sql, (project_id,))
        if not project_info:
            raise ValueError(f"未找到项目ID={project_id}的配置信息")

        client_code = project_info['client_code']
        item_year = project_info['item_year']
        split_tb_paper = project_info['split_tb_paper']
        
        logger.info(f"项目配置: client_code={client_code}, item_year={item_year}, split_tb_paper={split_tb_paper}")

        # 2. 查询问卷信息
        questionnaire_sql = f"""
        SELECT id, dy_target 
        FROM wt_template_customer 
        WHERE id IN ({','.join(['%s'] * len(questionnaire_ids))})
        """
        questionnaires = db.fetchall(questionnaire_sql, tuple(questionnaire_ids))
        if not questionnaires:
            raise ValueError(f"未找到问卷ID集合={questionnaire_ids}的配置信息")
        
        logger.info(f"查询到问卷信息: {questionnaires}")

        # 3. 过滤GRADUATE_MIDDLE调研对象的问卷
        valid_questionnaire_ids = [q['id'] for q in questionnaires if q['dy_target'] == 'GRADUATE_MIDDLE']
        if not valid_questionnaire_ids:
            raise ValueError("未找到目标调研对象(GRADUATE_MIDDLE)的问卷ID")
            
        logger.info(f"找到有效问卷ID: {valid_questionnaire_ids}")

        # 4. 查询问题信息
        question_sql = """
        SELECT id, wt_code, wt_obj 
        FROM wt_template_question_customer 
        WHERE cd_template_id = %s AND wt_code = %s AND is_del = 0
        """
        question_info = db.fetchone(question_sql, (valid_questionnaire_ids[0], 'T00024731'))
        if not question_info:
            raise ValueError("未找到指定问题编码(T00024731)的问题信息")
            
        logger.info(f"找到问题信息: ID={question_info['id']}, 编码={question_info['wt_code']}")

        # 5. 解析问题选项
        wt_obj = json.loads(question_info['wt_obj'])
        options = []
        for item in wt_obj['itemList']:
            options.append({
                'key': item['key'],
                'val': item['val'],
                'weight': item.get('weight', 0)
            })
        logger.info(f"解析问题选项: {options}")

        # 6. 构建答案表名
        answer_table = f"re_dy_paper_answer_{split_tb_paper}"

        # 7. 计算前三项占比前五项的值
        ratio_sql = f"""
        SELECT 
            (SUM(c1)+SUM(c2)+SUM(c3))/(SUM(c1)+SUM(c2)+SUM(c3)+SUM(c4)+SUM(c5)) as ratio_sum 
        FROM {answer_table} 
        WHERE cd_template_id = %s AND wid = %s AND ans_true = 1
        """
        ratio_result = db.fetchone(ratio_sql, (valid_questionnaire_ids[0], question_info['id']))
        if not ratio_result or ratio_result['ratio_sum'] is None:
            raise ValueError("未找到有效的答案数据")
        
        ratio = float(ratio_result['ratio_sum'])
        logger.info(f"计算得到前三项占比: {ratio:.4f}")

        # 8. 构建返回结果
        result_data = [{
            "key": "default",
            "val": f"{ratio:.4f}"
        }]

        logger.info(f"指标 '对课程设置与社会需求的契合度-总体' 计算成功")
        return {
            "success": True,
            "message": "ok",
            "code": 0,
            "result": [{
                "calcVals": [{
                    "val": result_data
                }]
            }]
        }

    except Exception as e:
        logger.error(f"计算指标 '对课程设置与社会需求的契合度-总体' 时发生错误: {str(e)}", exc_info=True)
        return {
            "success": False,
            "message": f"数据获取失败: 对课程设置与社会需求的契合度-总体",
            "code": 500,
            "error": str(e)
        }